using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using CPlatePrintSys.Win.Models;
using Prism.Commands;
using Prism.Mvvm;

namespace CPlatePrintSys.Win.ViewModels
{
    public class RoundingRuleAddOrEditViewModel : BindableBase
    {
        private readonly IGlobalConfigService _configService;
        private readonly Action<RoundingRuleModel> _onSaveCallback;

        // 关闭窗口事件
        public event Action CloseWindowRequested;

        // 规则对象
        private RoundingRuleModel _rule;
        public RoundingRuleModel Rule
        {
            get { return _rule; }
            set { SetProperty(ref _rule, value); }
        }

        // 是否为编辑模式
        private bool _isEditMode;
        public bool IsEditMode
        {
            get { return _isEditMode; }
            set { SetProperty(ref _isEditMode, value); }
        }

        // 标题
        private string _title;
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        // 错误信息
        private string _errorMessage;
        public string ErrorMessage
        {
            get { return _errorMessage; }
            set { SetProperty(ref _errorMessage, value); }
        }

        // 取整规则选项
        public List<string> RoundingRuleOptions { get; private set; }

        // 命令
        public ICommand SaveCommand { get; }
        public ICommand CancelCommand { get; }

        public RoundingRuleAddOrEditViewModel(IGlobalConfigService configService, RoundingRuleModel rule = null, Action<RoundingRuleModel> onSaveCallback = null)
        {
            _configService = configService;
            _onSaveCallback = onSaveCallback;

            // 初始化取整规则选项
            RoundingRuleOptions = CPlatePrintSys.Domain.Models.RoundingRuleOptions.GetAllOptions();

            SaveCommand = new DelegateCommand(Save);
            CancelCommand = new DelegateCommand(Cancel);

            if (rule != null)
            {
                // 编辑模式
                IsEditMode = true;
                Title = "编辑取整规则";
                Rule = new RoundingRuleModel
                {
                    RuleName = rule.RuleName,
                    RoundingMethod = rule.RoundingMethod,
                    IsDefault = rule.IsDefault
                };
            }
            else
            {
                // 添加模式
                IsEditMode = false;
                Title = "添加取整规则";
                Rule = new RoundingRuleModel
                {
                    RuleName = "",
                    RoundingMethod = CPlatePrintSys.Domain.Models.RoundingRuleOptions.FourRoundFiveUp,
                    IsDefault = false
                };
            }
        }

        private async void Save()
        {
            try
            {
                // 验证输入
                if (string.IsNullOrWhiteSpace(Rule.RuleName))
                {
                    ErrorMessage = "请输入加工序列名称";
                    return;
                }

                if (Rule.RuleName.Length < 3 || Rule.RuleName.Length > 10)
                {
                    ErrorMessage = "加工序列名称长度必须在3-10位之间";
                    return;
                }

                var config = await _configService.GetRoundingRuleConfigAsync();

                if (Rule.IsDefault)
                {
                    // 编辑默认规则
                    config.Default = Rule.RoundingMethod;
                }
                else
                {
                    // 检查名称是否已存在（编辑模式下排除自身）
                    var existingRule = config.Stages.Keys.FirstOrDefault(k => 
                        k.Equals(Rule.RuleName, StringComparison.OrdinalIgnoreCase) && 
                        (!IsEditMode || k != Rule.RuleName));

                    if (existingRule != null)
                    {
                        ErrorMessage = "该加工序列已存在";
                        return;
                    }

                    // 保存规则
                    if (IsEditMode)
                    {
                        // 编辑模式：更新现有规则
                        if (config.Stages.ContainsKey(Rule.RuleName))
                        {
                            config.Stages[Rule.RuleName] = Rule.RoundingMethod;
                        }
                    }
                    else
                    {
                        // 添加模式：添加新规则
                        config.Stages[Rule.RuleName] = Rule.RoundingMethod;
                    }
                }

                await _configService.UpdateRoundingRuleConfigAsync(config, "System");

                // 调用回调函数
                _onSaveCallback?.Invoke(Rule);

                // 关闭窗口
                CloseWindow();
            }
            catch (Exception ex)
            {
                ErrorMessage = $"保存失败: {ex.Message}";
            }
        }

        private void Cancel()
        {
            CloseWindow();
        }

        private void CloseWindow()
        {
            CloseWindowRequested?.Invoke();
        }
    }
} 